package com.btr.ivle.backgroud;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.btr.ivle.R;
import com.btr.ivle.data.ForumData;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.MapComparator;
import com.btr.ivle.helper.URLtoString;

public class GetForumTask extends AsyncTask<String, Void, Boolean>{
	
	private Context context;
	private boolean isNewPost;
	
	public GetForumTask(Context context){
		this.context = context;
	}

	protected Boolean doInBackground(String... texts) {
		boolean isEmpty = true;
		String ForumID = texts[0];
		Map<String, String> map;
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		
		try{
        	URL url = new URL("https://ivle.nus.edu.sg/api/Lapi.svc/Forum_Headings?APIKey=" +
        			context.getString(R.string.IVLE_API_KEY) + "&AuthToken=" + IVLEToken.getToken() + "&ForumID="
        				+ ForumID + "&Duration=0&IncludeThreads=true");
        	
        	JSONObject jObject = new JSONObject(URLtoString.get(url));
	        JSONArray resultsArrary = jObject.getJSONArray("Results");
	        List<Map<String, String>> listThread, listSubThread;
	        Comparator<Map<String, String>> mapComparator = new MapComparator("PostDate", false);
	        Comparator<Map<String, String>> mapComparatorDes = new MapComparator("PostDate", true);
	        String ID;
	        
	        //every header
	        for (int i = 0; i < resultsArrary.length(); i++) {
	        	map = new HashMap<String, String>();
	        	map.put("ID", resultsArrary.getJSONObject(i).getString("ID").toString());
	        	map.put("Title", resultsArrary.getJSONObject(i).getString("Title").toString());
	        	list.add(map);
	        	
	        	JSONArray threads = resultsArrary.getJSONObject(i).getJSONArray("Threads");
	        	listThread = new ArrayList<Map<String, String>>();
	        	if(threads.length()>0)
	        		isEmpty = false;
	        	
	        	//every first level thread
	        	for(int j = 0; j < threads.length(); j++){
	        		isNewPost = false;
	        		map = new HashMap<String, String>();
	        		listSubThread = new ArrayList<Map<String, String>>();
	        		ID = threads.getJSONObject(j).getString("ID").toString();
	        		map.put("ID", ID);
	        		map.put("PostTitle", threads.getJSONObject(j).getString("PostTitle").toString());
	        		map.put("PostBody", threads.getJSONObject(j).getString("PostBody").toString());
	        		map.put("PostDate", threads.getJSONObject(j).getString("PostDate").toString().substring(6, 19));
	        		map.put("PosterName", threads.getJSONObject(j).getJSONObject("Poster").getString("Name").toString());
	        		map.put("PosterEmail", threads.getJSONObject(j).getJSONObject("Poster").getString("Email").toString());
	        		if(threads.getJSONObject(j).getBoolean("isPosterStaff")){
	        			map.put("isPosterStaff", null);
	        		}
	        		map.put("topLevel", null);
	        		listSubThread.add(map);
	        		
	        		JSONArray subThreads = threads.getJSONObject(j).getJSONArray("Threads");
	        		if(subThreads.length()>0)
	        			listSubThread.addAll(getThread(subThreads));
	        		Collections.sort(listSubThread, mapComparatorDes);
	        		ForumData.add(ID, listSubThread);
	        		
	        		if(!threads.getJSONObject(j).getBoolean("isRead")||isNewPost)
	        			map.put("isNewPost", null);
	        		listThread.add(map);
	        	}  	
        		Collections.sort(listThread, mapComparator);
        		list.addAll(listThread);
			}
		}catch(JSONException ex){
        	Log.e("JSONException", ex.getMessage());
	    }catch(Exception ex){
        	//Log.e("Exception", ex.getMessage());
	    }
		ForumData.add(ForumID, list);
		return isEmpty;
	}
	
	private List<Map<String, String>> getThread(JSONArray threads) throws JSONException{
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map;
		
		for(int i = 0; i < threads.length(); i++){
    		map = new HashMap<String, String>();
    		
    		map.put("ID", threads.getJSONObject(i).getString("ID").toString());
    		map.put("PostTitle", threads.getJSONObject(i).getString("PostTitle").toString());
    		map.put("PostBody", threads.getJSONObject(i).getString("PostBody").toString().toString());
    		map.put("PostDate", threads.getJSONObject(i).getString("PostDate").toString().substring(6, 19));
    		map.put("PosterName", threads.getJSONObject(i).getJSONObject("Poster").getString("Name").toString());
    		map.put("PosterEmail", threads.getJSONObject(i).getJSONObject("Poster").getString("Email").toString());
    		if(threads.getJSONObject(i).getBoolean("isPosterStaff")){
    			map.put("isPosterStaff", null);
    		}
    		list.add(map);
    		
    		if(!threads.getJSONObject(i).getBoolean("isRead"))
    			isNewPost = true;
    		
    		JSONArray childThreads = threads.getJSONObject(i).getJSONArray("Threads");
    		if(childThreads.length()>0)
    			list.addAll(getThread(childThreads));
    	}
		return list;
	}
	
	@SuppressWarnings("unchecked")
    protected void onPostExecute(Boolean result) {	
		AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete(""); 
    }
}
